package com.yzc.mihuyou.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@Component
public class MailClient {
    @Autowired
    private JavaMailSender mailSender;

    public String sendMail(String to, String subject) {
        String tokre=createVertifyCode();
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);
            helper.setFrom("3097089520@qq.com");
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(tokre, true);
            mailSender.send(helper.getMimeMessage());
        } catch (MessagingException e) {
            return "邮箱账号有误";
        }
        return tokre;
    }

    //  获取6位随机验证码
    public String createVertifyCode(){
        String[] letters = new String[] {
                "q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m",
                "A","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M",
                "0","1","2","3","4","5","6","7","8","9"};
        String stringBuilder ="";
        for (int i = 0; i < 6; i++) {
            stringBuilder = stringBuilder + letters[(int)Math.floor(Math.random()*letters.length)];
        }
        return stringBuilder;
    }
}
